import * as vscode from 'vscode';
import { SnippetManager } from '../utils/snippetManager';
import { SnippetProvider } from '../providers/snippetProvider';

export class EditSnippetCommand {
    constructor(
        private snippetManager: SnippetManager,
        private snippetProvider: SnippetProvider
    ) {}

    get commandId(): string {
        return 'snippetManager.editSnippet';
    }

    async execute(item?: any): Promise<void> {
        try {
            let snippet = item?.snippet;
            if (!snippet) {
                // 如果没有提供snippet，让用户选择
                const snippets = this.snippetManager.getAllSnippets();
                if (snippets.length === 0) {
                    vscode.window.showInformationMessage('No snippets to edit');
                    return;
                }

                const items = snippets.map(s => ({
                    label: s.name,
                    description: `${s.group} • ${s.description}`,
                    snippet: s
                }));

                const selected = await vscode.window.showQuickPick(items, {
                    placeHolder: 'Select a snippet to edit...'
                });

                if (!selected) return;
                snippet = selected.snippet;
            }

            // 编辑各个字段
            const name = await vscode.window.showInputBox({
                prompt: 'Edit snippet name',
                value: snippet.name,
                validateInput: value => value ? null : 'Name is required'
            });
            if (!name) return;

            const description = await vscode.window.showInputBox({
                prompt: 'Edit description',
                value: snippet.description
            });
            if (!description) return;

            const languages = [
                'javascript', 'typescript', 'python', 'java', 'cpp', 'csharp', 'php', 'go', 'rust', 'html', 'css', 'json', 'markdown'
            ];
            const language = await vscode.window.showQuickPick(languages, {
                placeHolder: 'Select language',
                value: snippet.language
            });
            if (!language) return;

            const group = await vscode.window.showInputBox({
                prompt: 'Edit group name',
                value: snippet.group,
                validateInput: value => value ? null : 'Group is required'
            });
            if (!group) return;

            const tagsInput = await vscode.window.showInputBox({
                prompt: 'Edit tags (comma-separated)',
                value: snippet.tags.join(', ')
            });
            const tags = tagsInput ? tagsInput.split(',').map(t => t.trim()).filter(t => t) : [];

            // 在编辑器中编辑代码
            const doc = await vscode.workspace.openTextDocument({
                language: snippet.language,
                content: snippet.code
            });

            const editor = await vscode.window.showTextDocument(doc);
            const editedCode = await new Promise<string | undefined>((resolve) => {
                const disposable = vscode.window.onDidChangeActiveTextEditor(() => {
                    disposable.dispose();
                    resolve(editor.document.getText());
                });

                vscode.window.showInformationMessage(
                    'Edit the snippet code in the editor, then close the tab to save changes',
                    'Save and Close'
                ).then(() => {
                    disposable.dispose();
                    resolve(editor.document.getText());
                });
            });

            if (!editedCode) return;

            // 更新代码片段
            await this.snippetManager.updateSnippet(snippet.id, {
                name,
                description,
                language,
                code: editedCode,
                tags,
                group
            });

            this.snippetProvider.refresh();
            vscode.window.showInformationMessage(`Snippet "${name}" updated successfully!`);

        } catch (error) {
            vscode.window.showErrorMessage(`Failed to edit snippet: ${error}`);
        }
    }
}
